from rest_framework import serializers
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from django.db import transaction
import base64
import uuid
from .models import TravelRecord, Comment, Like

class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

class TravelRecordSerializer(serializers.ModelSerializer):
    """旅游记录序列化器"""
    user = UserSerializer(read_only=True)
    comments_count = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    
    class Meta:
        model = TravelRecord
        fields = [
            'id', 'title', 'description', 'location', 
            'latitude', 'longitude', 'start_date', 'end_date', 'images',
            'main_image_index', 'created_at', 'updated_at', 'user',
            'comments_count', 'likes_count', 'is_liked'
        ]
        read_only_fields = ['created_at', 'updated_at', 'user']
    
    def get_comments_count(self, obj):
        return obj.comments.count()
    
    def get_likes_count(self, obj):
        return obj.likes.count()
    
    def get_is_liked(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.likes.filter(user=request.user).exists()
        return False
    
    @transaction.atomic
    def create(self, validated_data):
        """创建旅游记录（包含图片处理的事务）"""
        validated_data['user'] = self.context['request'].user
        
        # 处理base64图片数据
        images_data = validated_data.pop('images_data', [])
        # 移除可能存在的deleted_images和existing_images字段（创建时不应该有）
        validated_data.pop('deleted_images', None)
        validated_data.pop('existing_images', None)
        
        instance = super().create(validated_data)
        
        # 处理图片上传
        processed_images = []
        for image_data in images_data:
            try:
                image_url = self._process_image_data(image_data)
                processed_images.append(image_url)
            except Exception as e:
                # 事务会自动回滚
                raise serializers.ValidationError(f"图片上传失败: {str(e)}")
        
        # 更新图片列表
        if processed_images:
            instance.images = processed_images
            instance.save()
        
        return instance

    @transaction.atomic
    def update(self, instance, validated_data):
        """更新旅游记录（包含图片处理的事务）"""
        # 处理base64图片数据、现有图片和删除的图片
        images_data = validated_data.pop('images_data', [])
        existing_images = validated_data.pop('existing_images', [])
        deleted_images = validated_data.pop('deleted_images', [])
        instance = super().update(instance, validated_data)
        
        # 删除物理文件
        for image_url in deleted_images:
            try:
                if image_url.startswith('https://'):
                    # 提取文件路径
                    file_path = image_url.split('/media/')[1]
                    if default_storage.exists(file_path):
                        default_storage.delete(file_path)
            except Exception as e:
                # 记录错误但继续处理，避免影响其他操作
                print(f"删除图片文件失败: {image_url}, 错误: {str(e)}")
        
        # 处理新图片上传和保留现有图片
        processed_images = existing_images  # 直接使用前端传来的现有图片
        for image_data in images_data:
            try:
                image_url = self._process_image_data(image_data)
                processed_images.append(image_url)
            except Exception as e:
                # 事务会自动回滚
                raise serializers.ValidationError(f"图片上传失败: {str(e)}")
        
        # 更新图片列表
        instance.images = processed_images
        instance.save()
        
        return instance
    
    def to_internal_value(self, data):
        """提取图片数据到单独的字段"""
        internal_value = super().to_internal_value(data)
        
        # 从请求数据中提取base64图片数据和现有URL图片
        images_data = []
        existing_images = []
        if 'images' in data and isinstance(data['images'], list):
            for image in data['images']:
                if isinstance(image, str):
                    if image.startswith('data:image/'):
                        images_data.append(image)
                    elif image.startswith('https://'):
                        existing_images.append(image)
        
        # 提取要删除的图片URL
        deleted_images = []
        if 'deleted_images' in data and isinstance(data['deleted_images'], list):
            deleted_images = [img for img in data['deleted_images'] if isinstance(img, str)]
        
        # 移除原始的images字段，避免base64数据被保存到数据库
        if 'images' in internal_value:
            del internal_value['images']
        
        internal_value['images_data'] = images_data
        internal_value['existing_images'] = existing_images
        internal_value['deleted_images'] = deleted_images
        return internal_value

    def _process_image_data(self, image_data):
        """处理base64图片数据并返回URL"""
        if 'base64,' in image_data:
            image_data = image_data.split('base64,')[1]
        
        image_data = base64.b64decode(image_data)
        
        # 生成唯一文件名
        file_name = f"travel_images/{uuid.uuid4()}.jpg"
        
        # 保存文件
        file_path = default_storage.save(file_name, ContentFile(image_data))
        
        # 构建完整的URL
        production_host = next((host for host in settings.ALLOWED_HOSTS if host != '*'), settings.ALLOWED_HOSTS[0])
        return f"https://{production_host}/media/{file_path}"

class CommentSerializer(serializers.ModelSerializer):
    """评论序列化器"""
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = Comment
        fields = ['id', 'content', 'created_at', 'user', 'travel_record']
        read_only_fields = ['created_at', 'user', 'travel_record']
    
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)

class LikeSerializer(serializers.ModelSerializer):
    """点赞序列化器"""
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = Like
        fields = ['id', 'created_at', 'user', 'travel_record']
        read_only_fields = ['created_at', 'user', 'travel_record']
    
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)
